import { Input } from "antd";
import { ChangeEvent, FC, useEffect, useState } from "react";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { LIST_SEARCH_PARAM_KEY } from "../../constant";

const { Search } = Input;

const ListSearch: FC = () => {
  const [searchText, setSearchText] = useState("");
  const nav = useNavigate();
  const { pathname } = useLocation();
  const [searchParams] = useSearchParams();

  useEffect(() => {
    const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || "";
    setSearchText(keyword);
  }, [searchParams]);

  const handleSearch = (value: string) => {
    // 需要将搜索值以 query 形式放到 url 上
    // 这样刷新之后也能保持搜索状态
    // 包括页码也是这样，放到 url 上，由 url 保持状态，其他组件监听 url 变化，等于有一个统一的上曾
    nav({
      pathname,
      search: `${LIST_SEARCH_PARAM_KEY}=${value}`,
    });
  };

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setSearchText(e.target.value);
  };

  return (
    <div>
      <Search
        value={searchText}
        size="large"
        placeholder="输入关键字"
        style={{ width: "300px" }}
        allowClear
        enterButton
        onChange={handleChange}
        onSearch={handleSearch}
      />
    </div>
  );
};

export default ListSearch;
